package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.CxSelect;
import com.ruoyi.common.core.domain.entity.SysMember;
import com.ruoyi.common.utils.CovertUtil;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.ISysFilterService;
import com.ruoyi.system.service.ISysOsssetService;
import com.ruoyi.system.service.ISysTypeService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.ISysDocService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2024-09-04
 */
@Controller
@RequestMapping("/system/doc")
public class SysDocController extends BaseController {
    private String prefix = "system/doc";

    @Autowired
    private ISysDocService sysDocService;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysTypeService iSysTypeService;
    @Autowired
    ISysFilterService iSysFilterService;
    @Autowired
    private ISysOsssetService sysOsssetService;
    @RequiresPermissions("system:doc:view")
    @GetMapping()
    public String doc() {
        return prefix + "/doc";
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @RequiresPermissions("system:doc:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysDoc sysDoc) {
        startPage();
        List<SysDoc> list = sysDocService.selectSysDocList1(sysDoc);
        SysOssset sysOssset;
        sysOssset = sysOsssetService.selectSysOsssetList(new SysOssset()).get(0);
        for (int i = 0; i < list.size(); i++) {
            String docpath = list.get(i).getPath();
            String pre = Constants.RESOURCE_PREFIX;
            String path = docpath.replace(pre+"/","");
             Long hcount = (long) CovertUtil.countFilesWithExtension(new File(StringUtils.getdir(list.get(i).getPath())), ".view");
            if(sysOssset.getState()>0&&ossFileExist(path))
            {
                String aliyun_src = path.substring(0,path.indexOf(".")) + "/";
                OSS ossClient = new OSSClientBuilder().build(sysOssset.getEndpoint(), sysOssset.getKeyid(), sysOssset.getKeysecret());
                ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(sysOssset.getBucket()).withMaxKeys(1000).withPrefix(aliyun_src));
                List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
                int fileCount = sums.size()-1;
                hcount = fileCount + hcount;
                ossClient.shutdown();
            }
            list.get(i).setPcount(hcount);
            list.get(i).setDocsize(FileUtils.convertFileSizeToString(list.get(i).getSize()));
            /*if (StringUtils.localFile(list.get(i).getPath()))
                list.get(i).setPath(serverConfig.getUrl() + StringUtils.localpng(list.get(i).getPath()));*/
            if(StringUtils.localFile(list.get(i).getPath())) {
                list.get(i).setPath(serverConfig.getUrl() + StringUtils.localpng(list.get(i).getPath()));
            }
            else if(sysOssset.getState()>0&&ossFileExist(StringUtils.osspng(list.get(i).getPath())))
            {
                list.get(i).setPath("https://"+sysOssset.getBucket()+"."+sysOssset.getEndpoint()+"/"+StringUtils.osspng(list.get(i).getPath()));
            }
            else
            {
                list.get(i).setPath("/img/doc.png");
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:doc:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysDoc sysDoc) {
        List<SysDoc> list = sysDocService.selectSysDocList(sysDoc);
        ExcelUtil<SysDoc> util = new ExcelUtil<SysDoc>(SysDoc.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @RequiresPermissions("system:doc:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(SysDoc sysDoc) {
        return toAjax(sysDocService.insertSysDoc(sysDoc));
    }

    /**
     * 修改【请填写功能名称】
     */
    @RequiresPermissions("system:doc:edit")
    @GetMapping("/edit/{docid}")
    public String edit(@PathVariable("docid") Long docid, ModelMap mmap) {
        SysDoc sysDoc = sysDocService.selectSysDocByDocid(docid);
        mmap.put("typeid", sysDoc.getTypeid());
        SysType sysType = iSysTypeService.selectSysTypeByTypeid(sysDoc.getTypeid());
        SysType sysType1 = iSysTypeService.selectSysTypeByTypeid(sysType.getPtypeid());
        mmap.put("typeid1", sysType.getPtypeid());
        mmap.put("typeid2", sysType1.getPtypeid());
        mmap.put("sysDoc", sysDoc);
        SysType typeFilter = iSysTypeService.selectSysTypeByTypeid(sysDoc.getTypeid());
        String filter = typeFilter.getFilter();
        String filterstr = "";
        String[] fi_arr = sysDoc.getFilter().split("\\.");
        if (!filter.isEmpty()) {
            String[] itemsArray = filter.split(",");
            for (int i = 0; i < itemsArray.length; i++) {
                Long pid = Long.parseLong(itemsArray[i]);
                SysFilter parentfiler = iSysFilterService.selectFilterById(pid);
                SysFilter sysFilter = new SysFilter();
                sysFilter.setPid(pid);
                List<SysFilter> sysFilterList = iSysFilterService.selectSysFilterList(sysFilter);
                String select = "<div class=\"form-group\"><label class=\"font-noraml\">" + parentfiler.getName() + "</label><select class=\"form-control\">" +
                        "<option value=\"\">--请选择--</option>";
                for (int j = 0; j < sysFilterList.size(); j++) {
                    if (Arrays.asList(fi_arr).contains(String.valueOf(sysFilterList.get(j).getId())))
                        select = select + "<option selected value=\"" + sysFilterList.get(j).getId() + "\">" + sysFilterList.get(j).getName() + "</option>";
                    else
                        select = select + "<option value=\"" + sysFilterList.get(j).getId() + "\">" + sysFilterList.get(j).getName() + "</option>";
                }
                select = select + "</select></div>";
                filterstr = filterstr + select;
            }

        }
        mmap.put("items", fi_arr);
        mmap.put("filter", filterstr);
        return prefix + "/edit";
    }

    @PostMapping("/getfilter")
    @ResponseBody
    public String filter(@RequestParam("typeid") long typeid) {
        SysType typeFilter = iSysTypeService.selectSysTypeByTypeid(typeid);
        String filter = typeFilter.getFilter();
        String filterstr = "";
        if (!filter.isEmpty()) {
            String[] itemsArray = filter.split(",");
            for (int i = 0; i < itemsArray.length; i++) {
                Long pid = Long.parseLong(itemsArray[i]);
                SysFilter parentfiler = iSysFilterService.selectFilterById(pid);
                SysFilter sysFilter = new SysFilter();
                sysFilter.setPid(pid);
                List<SysFilter> sysFilterList = iSysFilterService.selectSysFilterList(sysFilter);
                String select = "<div class=\"form-group\"><label class=\"font-noraml\">" + parentfiler.getName() + "</label><select class=\"form-control\">" +
                        "<option value=\"\">--请选择--</option>";
                for (int j = 0; j < sysFilterList.size(); j++) {
                    select = select + "<option value=\"" + sysFilterList.get(j).getId() + "\">" + sysFilterList.get(j).getName() + "</option>";
                }
                select = select + "</select></div>";
                filterstr = filterstr + select;
            }

        }
        return filterstr;
    }

    /**
     * 模拟数据
     */
    @GetMapping("/edit/cityData")
    @ResponseBody
    public String cityData() {
        SysType sysType = new SysType();
        sysType.setPtypeid(0l);
        List<SysType> sysTypeList = iSysTypeService.selectSysTypeList(sysType);
        List<CxSelect> tmList = new ArrayList<CxSelect>();
        for (int i = 0; i < sysTypeList.size(); i++) {
            CxSelect cxSelectTB = new CxSelect();
            cxSelectTB.setN(sysTypeList.get(i).getTypename());
            cxSelectTB.setV(sysTypeList.get(i).getTypeid().toString());
            SysType sysType1 = new SysType();
            sysType1.setPtypeid(sysTypeList.get(i).getTypeid());
            List<SysType> sysTypeList1 = iSysTypeService.selectSysTypeList(sysType1);
            List<CxSelect> tmList1 = new ArrayList<CxSelect>();
            for (int j = 0; j < sysTypeList1.size(); j++) {
                CxSelect cxSelectTm = new CxSelect();
                cxSelectTm.setN(sysTypeList1.get(j).getTypename());
                cxSelectTm.setV(sysTypeList1.get(j).getTypeid().toString());
                SysType sysType2 = new SysType();
                sysType2.setPtypeid(sysTypeList1.get(j).getTypeid());
                List<SysType> sysTypeList2 = iSysTypeService.selectSysTypeList(sysType2);
                List<CxSelect> tmList2 = new ArrayList<CxSelect>();
                for (int k = 0; k < sysTypeList2.size(); k++) {
                    CxSelect cxSelectjd = new CxSelect();
                    cxSelectjd.setN(sysTypeList2.get(k).getTypename());
                    cxSelectjd.setV(sysTypeList2.get(k).getTypeid().toString());
                    tmList2.add(cxSelectjd);
                }
                cxSelectTm.setS(tmList2);
                tmList1.add(cxSelectTm);

            }
            cxSelectTB.setS(tmList1);
            tmList.add(cxSelectTB);

        }
        return JSONObject.toJSONString(tmList);
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("system:doc:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(SysDoc sysDoc) {
        return toAjax(sysDocService.editSysDoc(sysDoc));
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:doc:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        String[] itemsArray = ids.split(",");
        for (int i = 0; i < itemsArray.length; i++) {
            if (!StringUtils.isEmpty(itemsArray[i])) {
                /*Long docid = Long.parseLong(itemsArray[i]);
                SysDoc sysDoc = sysDocService.selectSysDocByDocid(docid);
                String docpath = sysDoc.getPath();
                sysDocService.deleteSysDocByDocid(docid); //刪除
                String pre = Constants.RESOURCE_PREFIX;
                String dirname = RuoYiConfig.getProfile();
                String srcurl = dirname + docpath.replace(pre, "");
                String srcpath = srcurl.substring(0, srcurl.indexOf(".")) + "/";
                FileUtils.deleteFile(srcurl);
                FileUtils.deleteFolder(new File(srcpath));
                 */
                Long docid = Long.parseLong(itemsArray[i]);
                SysDoc sysDoc = sysDocService.selectSysDocByDocid(docid);
                String docpath = sysDoc.getPath();
                sysDocService.deleteSysDocByDocid(docid); //刪除
                String pre = Constants.RESOURCE_PREFIX;
                String dirname = RuoYiConfig.getProfile();
                String srcurl = dirname + docpath.replace(pre,"");
                String path = docpath.replace(pre+"/","");
                String aliyun_src = path.substring(0,path.indexOf(".")) + "/";
                SysOssset sysOssset;
                sysOssset = sysOsssetService.selectSysOsssetList(new SysOssset()).get(0);
                OSS ossClient = new OSSClientBuilder().build(sysOssset.getEndpoint(), sysOssset.getKeyid(), sysOssset.getKeysecret());
                if(new File(srcurl).exists()) {
                    String srcpath  = srcurl.substring(0,srcurl.indexOf(".")) + "/";
                    FileUtils.deleteFile(srcurl);
                    FileUtils.deleteFolder(new File(srcpath));
                }
                else if(sysOssset.getState()>0&&ossFileExist(path)) {
                    ossClient.deleteObject(sysOssset.getBucket(), path);
                    String dirPrefix = aliyun_src; // 假设你要删除的是名为"folder"的目录下的所有文件
                    ListObjectsRequest listObjectsRequest = new ListObjectsRequest(sysOssset.getBucket()).withPrefix(dirPrefix);
                    listObjectsRequest.setMaxKeys(1000); // 最大返回1000个结果，根据需要调整
                    List<String> keysToDelete = new ArrayList<>();
                    for (OSSObjectSummary objectSummary : ossClient.listObjects(listObjectsRequest).getObjectSummaries()) {
                        keysToDelete.add(objectSummary.getKey()); // 添加每个对象的key到列表中，以便一次性删除
                    }
                    if (!keysToDelete.isEmpty()) {
                        DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(sysOssset.getBucket()).withKeys(keysToDelete);
                        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
                        System.out.println("Deleted objects: " + deleteObjectsResult.getDeletedObjects());
                    } else {
                        System.out.println("No objects to delete.");
                    };
                    ossClient.deleteObject(sysOssset.getBucket(), aliyun_src);
                    ossClient.shutdown();
                }
                return toAjax(1);
            }
        }
        return toAjax(-1);
    }
    protected   Boolean ossFileExist(String strfile) {
        SysOssset sysOssset;
        sysOssset = sysOsssetService.selectSysOsssetList(new SysOssset()).get(0);
        OSS ossClient = new OSSClientBuilder().build(sysOssset.getEndpoint(), sysOssset.getKeyid(), sysOssset.getKeysecret());
        return  ossClient.doesObjectExist(sysOssset.getBucket(), strfile);
    }
    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:doc:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping("/change")
    @ResponseBody
    public AjaxResult change(String ids) throws Exception {
        String[] itemsArray = ids.split(",");
        for (int i = 0; i < itemsArray.length; i++) {
            if (!StringUtils.isEmpty(itemsArray[i])) {
                Long docid = Long.parseLong(itemsArray[i]);
                String docpath = sysDocService.selectSysDocByDocid(docid).getPath();
                String pre = Constants.RESOURCE_PREFIX;
                String dirname = RuoYiConfig.getProfile();
                String srcurl = dirname + docpath.replace(pre,"");
                File file = new File(srcurl);
                String filename = file.getName().substring(0,file.getName().indexOf("."));
                String srcpath  = srcurl.substring(0,srcurl.indexOf(".")) + "/";
                String strpath  = srcpath + filename +".pdf";
                String extName = file.getName().substring(file.getName().lastIndexOf(".") + 1);
                if(extName.equals("docx") || extName.equals("doc") || extName.equals("wps") || extName.equals("rtf") || extName.equals("ofd")) {
                    CovertUtil.fileToPdf(srcurl,strpath,"0",srcpath,10);
                } else if(extName.equals("epub"))
                {
                    CovertUtil.EpubToPdf(srcurl,strpath,"0",srcpath);

                }
                else if(extName.equals("ppt") || extName.equals("pptx") || extName.equals("dps") || extName.equals("pps") || extName.equals("pot")) {
                    CovertUtil.fileToPdf(srcurl,strpath,"1",srcpath,10);

                }else if(extName.equals("txt"))
                {
                    CovertUtil.txtToPdf(srcurl,strpath,"0",srcpath);

                }  else if(extName.equals("pdf"))
                {
                    CovertUtil.downPdf(srcurl,strpath,"0",srcpath);

                }
                else if(extName.equals("csv"))
                {
                    CovertUtil.fileToPdf(srcurl,strpath,"3",srcpath,10);

                }
                else
                {
                    CovertUtil.fileToPdf(srcurl,strpath,"2",srcpath,10);

                }
                if(!extName.equals("pdf"))
                {

                    if (new File(strpath).exists()) {
                        new File(strpath).delete();
                    }
                }

                return toAjax(1);
            }
        }
        return toAjax(-1);
    }
    @GetMapping (value = {"/download"})
    public ResponseEntity<ByteArrayResource> downdoc(@RequestParam("docid") long docid) throws IOException {
        SysDoc doc = sysDocService.selectSysDocByDocid(docid);
        String docpath = doc.getPath();
        String pre = Constants.RESOURCE_PREFIX;
        String dirname = RuoYiConfig.getProfile();
        String srcurl = dirname + docpath.replace(pre,"");
        String soucename = doc.getTitle() + "." + doc.getExten();
        byte[] bytes = Files.readAllBytes(new File(srcurl).toPath());

        ByteArrayResource bar = new ByteArrayResource(bytes);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-disposition", "attachment; filename=\"" + URLEncoder.encode(soucename) + "\";charset=utf-8")
                .body(bar);

    }
}
